package db

import (
	"database/sql"
	"fmt"
)

//go:generate mockgen -destination=userdb_mack.go -package=db -source=userdb.go UserDBI
type UserDBI interface {
	Get(name string, password string) (*User, error)
}

type UserDB struct {
	db *sql.DB
}

type User struct {
	Name string
	Password string
}

func NewUserDB(user string, password string, host string, port int, db string) (UserDBI, error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", user, password, host, port, db)

	var userDB UserDB
	var err error

	userDB.db, err = sql.Open("mysql", dsn)

	if err != nil {
		return nil, err
	}

	return &userDB, nil
}

// Get 根据 UserID 获取用户资料
func (udb *UserDB) Get(name string, password string) (*User, error) {
	s := "SELECT * FROM user WHERE name = ? AND password = ?"
	stmt, err := udb.db.Prepare(s)
	if err != nil {
		return nil, err
	}

	defer stmt.Close()

	var user User
	err = stmt.QueryRow(name, password).Scan(&user)
	if err != nil {
		return nil, err
	}

	return &user, nil
}
